<template>
  <div class="setting-content inside-comment">
    <h2 class="setting-header">
      <strong>课程目录</strong>
      <p><span>当前课程：</span>{{courseData.name}}</p>
    </h2>
    <div class="leacturer-list">
      <p>已绑定讲师：</p>
      <div class="leacturer-item" v-for="item in instanceLeacturerList" :key="item.id">
        <div class="lecturer-avatar">
          <img :src="item.avatar" v-if="item.avatar" alt="">
        </div>
        <div class="name">{{item.name}}</div>
      </div>
    </div>
    <div class="top-info">
      <div class="left-but">
        <el-button type="primary" @click="addChapter">增加章节</el-button>
        <el-dropdown trigger="click">
          <el-button type="primary" style="width: 100px;margin-left: 10px;">
            {{theInstance?.name}}<el-icon class="el-icon--right" style="margin-left: 5px;"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="item in instanceList" :key="item.id" @click="togInstance(item)">{{item.name}}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="right-box">
        <el-button type="primary" @click="showCourseLeacturer = true">设置讲师</el-button>
        <el-button type="primary" @click="toCourseStudent">本期学员</el-button>
        <el-button type="primary" @click="showCourseRate = true">课程评价</el-button>
        <el-button type="primary" @click="showCourseInstance = true">管理期数课程</el-button>
      </div>
    </div>
    <!-- 章节目录 表头 -->
    <div class="table-header">
      <span v-for="(item, index) in columns" :key="index" class="table-header-label" :style="{ width: item.width, flex: item.width ? 'none' : '1' }">
        {{ item.label }}
      </span>
    </div>
     <!-- 树形表格 -->
    <el-tree ref="treeRef" 
      v-if="catalogueTree && catalogueTree.length > 0" 
      :data="catalogueTree" 
      :props="defaultProps" 
      node-key="id" 
      default-expand-all  
      draggable 
      :allow-drop="allowDrop" 
      @node-drop="handleDrop" 
      @node-expand="handleNodeExpand" 
      @node-collapse="handleNodeCollapse" 
      @node-drag-end="handleNodeDragEnd"
      class="category-tree" 
      v-loading="treeLoading"
    >
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <!-- 名称列 固定宽度 -->
          <span class="tree-cell name-cell" :style="{ paddingLeft: (node.level) * 20 + 'px'}">
            <template v-if="showLevel">{{ `${data.level} - ` }}</template>{{ data.name }}
          </span>
          <!-- 说明 -->
          <span class="tree-cell description-cell" >
            {{ data.description }}
          </span>
          <!-- 类型  -->
          <span class="tree-cell type-cell">
            <el-tag v-if="data.type == 'CHAPTER'" type="primary">章节</el-tag>
            <el-tag v-if="data.type == 'VIDEO'" type="success">视频</el-tag>
            <el-tag v-if="data.type == 'DOCUMENT'" type="success">文档</el-tag>
            <el-tag v-if="data.type == 'EXERCISE'" type="success">练习</el-tag>
            <el-tag v-if="data.type == 'ASSESSMENT'" type="success">测试</el-tag>
          </span>
          <!-- 绑定资源  -->
          <span class="tree-cell exam-cell">
            <span v-if="data.type != 'CHAPTER'">{{ data.dataId ? '已设置' : '否' }}</span>
          </span>
          <!-- 设置学中测试  -->
          <span class="tree-cell test-cell">
            <span v-if="data.type == 'VIDEO'">{{ data.learningTests ? '已设置' : '否' }}</span>
          </span>
          <!-- 操作  -->
          <div class="tree-cell operation-cell">
            <div class="button-box">
              <el-button type="primary" link @click.stop="editChapterInfo(data)">编辑</el-button>
              <el-button :disabled="!(data.type == 'CHAPTER')" type="primary" link @click.stop="addChapter(data)">添加</el-button>
              <el-button type="primary" link @click.stop="remove(data)">删除</el-button>
              <!-- <el-dropdown trigger="hover">
                <i class="iconfont">&#xe771;</i>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item type="primary" plain size="small" @click="handleView(row)">
                      <i class="iconfont">&#xe6ef;</i>
                      前台浏览
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown> -->
            </div>
          </div>
        </div>
      </template>
    </el-tree>
    <el-empty v-else description="暂无数据" />
    <!-- 章节信息编辑 对话框 -->
    <el-dialog v-model="addChapterVisible" :title="addChapterFlag?'新增章节':'编辑章节信息'" width="600px" class="addChapter-dialog">
      <el-form :model="addChapterForm" :rules="rules" label-width="80px">
        <el-form-item label="上级章节" prop="pid" v-if="chapterPid">
          <!-- <el-cascader :options="catalogueTree" :props="props1" v-model="addChapterForm.pid" :show-all-levels="false"  placeholder="选择上级"/> -->
          <el-cascader :options="catalogueTree" :props="props1" v-model="addChapterForm.pid" :show-all-levels="false" popper-class="pid-cascader" placeholder="选择上级">
            <template #default="{ data }">
              <p @click="handleChooseParent(data,data.type != 'CHAPTER')"  :class="{ 'disabled-item': data.type !== 'CHAPTER' }" class="cascader-p">{{data.title}}</p>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item label="章节名称" prop="name">
          <el-input placeholder="输入章节名称" v-model="addChapterForm.name"></el-input>
        </el-form-item>
        <el-form-item label="章节类型" prop="type">
          <!-- 这里如果有子目录了，章节类型不允许修改 -->
          <el-select v-model="addChapterForm.type" placeholder="选择章节类型" @change="changeFileType" :disabled="addChapterForm.children && addChapterForm.children.length > 0">
            <el-option
              v-for="item in courseTypeOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <div class="tips">说明：只有章节类型选择章节才能有子目录，并且只有视频才能设置学中测试</div>
        </el-form-item>
        <el-form-item label="设置试卷" prop="paper"  v-if="addChapterForm.type == 'EXERCISE' || addChapterForm.type == 'EXERASSESSMENTCISE' || addChapterForm.type == 'FINAL_EXAM'">
          <div class="exam-info"> 
            <el-form-item label="试卷名称" prop="label">
              <el-input v-model="addChapterForm.paperConfig.label" placeholder="请输入试卷名称" />
            </el-form-item>
            <el-form-item label="组卷开始时间" >
              <el-date-picker
                v-model="addChapterForm.autoComposingTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择自动组卷开始时间"
              />
            </el-form-item>
            <el-form-item label="组卷方式" prop="randomWay">
              <el-select v-model="addChapterForm.paperConfig.randomWay" placeholder="请选择随机组卷方式" style="width: 240px">
                <el-option label="基础试卷组卷" value="1" />
                <el-option label="自定义条件组卷" value="2" />
              </el-select>
            </el-form-item>
            <!-- 选择已有试卷  -->
            <div  v-if="addChapterForm.paperConfig.randomWay == 1">
              <el-form-item label="选择试卷" prop="originalIdList" >
                <el-select v-model="addChapterForm.paperConfig.originalIdList" multiple placeholder="请选择试卷" style="width: 240px">
                  <el-option label="试卷1" value="1" />
                  <el-option label="试卷2" value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="题目是否随机" prop="isTitleRandom">
                <el-switch v-model="addChapterForm.paperConfig.isTitleRandom" />
              </el-form-item>
            </div>
            <!-- 自定义组卷  -->
            <div  v-if="addChapterForm.paperConfig.randomWay == 2">
              <el-form-item label="选择题库" prop="bankIdList">
                <el-select v-model="addChapterForm.paperConfig.bankIdList" placeholder="请选择题库" style="width: 240px">
                  <el-option label="题库1" value="1" />
                  <el-option label="题库2" value="2" />
                </el-select>
              </el-form-item>
              <!-- 题目总分 根据题组的设置信息自动计算  -->
              <el-form-item label="总分" prop="totalScore">
                <el-input-number v-model="addChapterForm.totalScore" :min="1"  :step="1" :precision="0" disabled/>
              </el-form-item>
              <el-form-item label="及格分数" prop="qualifyScore">
                <el-input-number v-model="addChapterForm.qualifyScore" :min="1" :step="1" :precision="0" />
              </el-form-item>
              <el-form-item label="及格分占比" prop="passingScoreRate">
                <el-input-number v-model="addChapterForm.passingScoreRate" :min="1" :step="1" :precision="0" />
              </el-form-item>
              <div class="question-group-config">
                <el-divider />
                <!-- 题组参数设置  -->
                <div class="tip">
                  <p>题组设置</p>
                  <el-button type="primary" @click="addQuestionGroup" class="add-but">添加题组</el-button>
                </div>
                <div class="item-set-config" v-for="(item, index) in addChapterForm.paperConfig.customizationVo.itemSetConfigVoList" :key="index">
                  <div class="form-row">
                    <el-form-item label="题组名称" prop="setName">
                      <el-input v-model="item.setName" placeholder="请输入题组名称" style="width: 200px;"/>
                    </el-form-item>
                    <el-icon @click="delQuestionGroup(index)" class="del-icon"><Delete /></el-icon>
                  </div>
                  <div class="form-row">
                    <el-form-item class="row-item" label="题目数量" prop="itemNum">
                      <el-input-number v-model="item.itemNum" :min="1" :step="1" :precision="0" />
                    </el-form-item>
                    <el-form-item class="row-item" label="每题分数" prop="itemScore">
                      <el-input-number v-model="item.itemScore" :min="1" :step="1" :precision="0" />
                    </el-form-item>
                    <el-form-item  class="row-item" label="题型" prop="typeId">
                      <el-select v-model="item.typeId" placeholder="请选择题型" style="width: 160px">
                        <el-option label="单选题" value="1" />
                        <el-option label="多选题" value="2" />
                        <el-option label="判断题" value="3" />
                        <el-option label="填空题" value="4" />
                        <el-option label="简答题" value="5" />
                      </el-select>
                    </el-form-item>
                    <el-form-item  class="row-item" label="题目难度" prop="difficulty">
                      <el-select v-model="item.difficulty" placeholder="请选择题目难度" style="width: 160px">
                        <el-option label="简单" value="1" />
                        <el-option label="中等" value="2" />
                        <el-option label="困难" value="3" />
                      </el-select>
                    </el-form-item>
                  </div>
                 
                  <el-form-item label="是否仲裁" prop="useArbitration">
                    <el-switch v-model="item.useArbitration" />
                  </el-form-item>
                  <el-form-item label="仲裁分数" prop="arbitrationScore" v-if="item.useArbitration">
                    <el-input-number v-model="item.arbitrationScore" :min="1" :step="1" :precision="0" />
                  </el-form-item>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="学中测试" v-if="addChapterForm.type == 'VIDEO'">
          <div class="info-row">
            <el-button type="primary" @click="checkQuestionVisible = true">添加测试</el-button>
          </div>
          <div class="test-list" v-if="addChapterForm.learningTests && addChapterForm.learningTests.length > 0">
            <div class="test-item header" style="border-bottom: 1px solid #eee;">
              <div style="width: 100px;">进度</div>
              <div class="test-name">问题名称</div>
              <div class="right-option">操作</div>
            </div>
            <div class="test-item" v-for="(item, index) in addChapterForm.learningTests" :key="index">
              <el-input-number v-model="item.progress" :min="1" :max="100" style="width: 100px;" size="small" :step="1" step-strictly/>
              <div class="test-name">{{item.questionName}}</div>
              <div class="right-option">
                <el-icon title="预览" @click="priviewQuestion(item)"><View /></el-icon>
                <el-icon title="删除" @click="delQuestion(item)"><Delete /></el-icon>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="课程资源" prop="dataId" v-if="addChapterForm.type == 'VIDEO' || addChapterForm.type == 'DOCUMENT'">
          <div class="form-row">
            <el-button type="primary" @click.stop="showCheckFile">选择文件</el-button>
            <el-button type="primary" v-if="addChapterForm.dataId" @click.stop="preview(addChapterForm.dataId)">预览</el-button>
          </div>
          <div class="file-name" v-if="addChapterForm.fileName && addChapterForm.dataId != ''">
            <div>{{addChapterForm.fileName}}</div>
          </div>
        </el-form-item>
        <el-form-item label="章节说明" prop="description">
          <el-input placeholder="输入章节说明" v-model="addChapterForm.description"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addChapterVisible = false">取消</el-button>
          <el-button type="primary" @click="appendChapter">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑期数课程 -->
    <el-dialog v-model="showCourseInstance" title="管理期数课程" width="1100px" class="addChapter-dialog">
      <CourseInstance v-if="theCourseId" :theCourseId="theCourseId"/>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="confirmInstance">确认</el-button>
        </span>  
      </template>
    </el-dialog>

     <!-- 课程评分显示 -->
     <el-dialog v-model="showCourseRate" title="课程评价" width="1100px" class="addChapter-dialog">
      <el-scrollbar max-height="600px">
        <CourseRate v-if="showCourseRate && theCourseId" :courseId="theCourseId" />
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="showCourseRate = false">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 选择课程需要绑定的考试  -->
    <el-dialog v-model="checkExam" title="选择考试" width="1100px" class="addExam-dialog">
      <ExamList ref="examRef" v-if="checkExam && theCourseId" :courseInstanceId="courseIds" />
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="confrimCheckExam">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 选择课程绑定的讲师  -->
    <el-dialog v-model="showCourseLeacturer" title="绑定讲师" width="500px" class="add-dialog">
      <div class="leacturer-list" v-if="instanceLeacturerList && instanceLeacturerList.length > 0">
        <div class="leacturer-item" v-for="item in instanceLeacturerList" :key="item.id">
          <div class="lecturer-avatar">
            <img :src="item.avatar" v-if="item.avatar" alt="">
          </div>
          <div class="name">{{item.name}}</div>
          <el-icon class="nobind-icon" @click="nobindLeacturer(item)" title="解绑"><Close /></el-icon>
        </div>
      </div>
      <div class="option-row">
        <el-button type="primary" link @click="addLeaturer = true" class="add-leaturer">添加讲师</el-button>
        <el-select
          v-if="addLeaturer"
          v-model="addOneLeaturer"
          filterable
          placeholder="请选择要绑定的讲师"
          style="width: 240px"
          @change="addOneLeaturerChange"
        >
          <el-option
            v-for="item in leacturerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="confrimCheckExam">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 预览内容对话框 -->
    <el-dialog v-model="previewVisible" title="文件预览" width="900px" class="preview-dialog">
      <videoPlay
        v-if="previewInfo.fileType == '.mp4'"
        v-bind="videoOptions"
        :src="previewInfo.url"
        width="100%"
      ></videoPlay>
      <el-scrollbar height="540px" v-else>
        <!-- 判断文件类型，对应显示 -->
        <iframe
          v-if="previewInfo.fileType === '.pdf'"
          :src="previewInfo.url"
          width="100%"
          height="600px"
          frameborder="0"
        >
          <p>您的浏览器不支持预览此文档。</p>
        </iframe>
        <vue-office-pptx style="width: 100%" v-if="previewInfo.fileType == '.pptx'" :src="previewInfo.url"  @error="errorHandler"/>
        <vue-office-docx v-if="previewInfo.fileType == '.docx'" :src="previewInfo.url" />
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="previewVisible = false">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 题目预览 -->
    <el-dialog 
      v-model="testDialogVisible" 
      width="400px" 
      title="题目预览"
      :before-close="closeTheDialog" 
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="test-dialog" v-if="currentTestQuestion.length > 0">
        <h2>题目</h2>
        <!-- 当前页显示的题目 -->
        <el-form-item
          v-for="question in currentTestQuestion"
          :key="question.id"
          label-position="top"
        >
          <div class="question-content">
            <div class="question-description">
              【<span>{{question.cmp.compName}}</span>】{{question.cmp.label}}
            </div>
            <component
              :is="getComponent(question.cmp.type)"
              v-model:modelValue="question.answer"
              :setting="question.cmp"
            />
          </div>
        </el-form-item>
      </div>
      <template #footer>
        <span class="dialog-footer"> 
          <el-button type="primary" @click="testDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 上传文件 -->
    <el-dialog v-model="uploadVisible" title="文件上传" width="550px" class="preview-dialog">
      <el-form :model="saveResourceForm" label-width="80px">
        <el-form-item label="上传文件" prop="fileId">
          <el-button type="primary" @click.stop="showFilesUpload = true">选择文件</el-button>
          <div class="file-name" v-if="saveResourceForm.fileName && saveResourceForm.dataId != ''">{{saveResourceForm.fileName}}</div>
        </el-form-item>
        <el-form-item label="文件名称" prop="pid">
          <el-input placeholder="输入文件名称" v-model="saveResourceForm.name"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer"> 
          <el-button @click="cancelResource">取消</el-button>
          <el-button type="primary" @click="saveResource">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 学中测试设置 -->
    <el-dialog v-model="checkQuestionVisible" title="学中测试选择" width="800px" class="preview-dialog">
      <div class="check-question-container">
        <div class="left-tree">
          <el-scrollbar height="400px" style="padding-right: 10px;">
            <el-tree
              ref="testTree"
              :data="questionGroupTree"
              :props="{ label: 'title', children: 'clildList' }"
              node-key="id"
              highlight-current
              :accordion="true"
            >
              <template #default="{ data }">
                <div class="custom-tree-node" :class="{'active-level': data.id == currentGroup}" >
                  <span class="tree-cell" @click="data.clildList == null ? handleNodeClick(data) : null">
                    {{ data.title }}
                  </span>
                </div>
              </template>
            </el-tree>
          </el-scrollbar>
        </div>
        <div class="right-question-list">
          <SearchCmp style="margin-bottom: 10px;" v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="getTableData" />
          <RuifoxTable
            v-loading="tableLoading"
            :table-data="tableData"
            :field-list="fieldList"
            :default-index="true"
            :default-checkbox="false"
            :lazy="true"
          >
            <template #default-checkbox="{ element }">
              <div class="table-div-check">
                <el-checkbox
                  class="unmover"
                  v-model="element.checked"
                  @change="handleCheckTable(element.id)"
                  size=""
                />
              </div>
            </template>
            <template #name="{ element }">
              <span class="question-name">{{element?.cmp?.label}} </span>
            </template>
            <template #questionType="{ element }">
              {{element?.cmp?.compName}} 
            </template>
            <template #options="{ element }">
              <div class="table-td-option unmover">
                <el-button
                  type="primary"
                  link
                  @click="checkTest(element)"
                >
                  选择
                </el-button>
              </div>
            </template>
          </RuifoxTable>
          <PaginationViewSimple 
            :total="queryData.total" 
            :pageSize="queryData.pageSize" 
            :currentPage="queryData.currentPage" 
            @currentChange="handleCurrentChange" 
            @changeSize="handleSizeChange" 
          />
        </div>
      </div>
      <!-- <template #footer>
        <span class="dialog-footer"> 
          <el-button @click="checkQuestionVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmTest">确认</el-button>
        </span>
      </template> -->
    </el-dialog>
    <!-- 文件上传  -->
    <FilesUpload v-if="showFilesUpload" v-model:showDialog="showFilesUpload" :isPublic="true" @getFileList="insertFiles" :isToJpg="true" :limit="10" :allow="fileType" :sizeLimit="500"></FilesUpload>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import { ref, reactive, onMounted, nextTick, markRaw } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { 
  getCourseChapterTree,
  createChapter,
  updateChapter,
  deleteChapter,
  reorderSameLevelChapters,
 } from "@/api/chapter";
import { getResourceDataRefer } from "@/api/resource";
import { 
  selectByIdCourse, 
  getCourseInstanceLecturersLecturer, 
  pagingLecturer, 
  bindLecturer,
  unbindLecturer
 } from "@/api/course";
import { selectPageInstance } from '@/api/instance';
import { 
  selectAllQuestionByTreePaperBank, 
  selectBankQuestionPagePaperBank,
  selectByIdPaperQuestion 
} from "@/api/form";
import { videoPlay } from 'vue3-video-play';
import 'vue3-video-play/dist/style.css';
import VueOfficePptx from "@vue-office/pptx";
import VueOfficeDocx from '@vue-office/docx';
import { ArrowDown, Close, Delete, View } from '@element-plus/icons-vue';
import '@vue-office/docx/lib/index.css';
import { tableList as mixTable } from "@ruifox-cms/utils";
import CourseInstance from "../../components/CourseInstance";
import CourseRate from "../../components/CourseRate";
import ExamList from "../../components/ExamList";
import FormCheckbox from '../../components/formItems/FormCheckbox.vue'
import FormRadio from '../../components/formItems/FormRadio.vue'
import { FilesUpload } from "@ruifox-cms/components";

// 组件注册
const components = ref({
  radio: markRaw(FormRadio),
  checkbox: markRaw(FormCheckbox),
})

const getComponent = (type) => {
  console.log("components.value[type]",components.value[type]);
  
  return components.value[type] || null
}
const route = useRoute(); 
const router = useRouter(); 
const theCourseId = route.query.id; 
const courseIds = [route.query.id]; 
const theInstance = ref()

//跳转学员列表页
const toCourseStudent = () => { 
  console.log("跳转学员列表");
  router.push({
    name: 'examManageCourseCourseStudent',
    query: {
      id: theInstance.value.id,
      name: courseData.value.name
    },
  })
}

//*****表单题目显示
const checkQuestionVisible = ref(false)
const questionGroupTree = ref([])
// const questionList = ref([]) 
const currentGroup = ref()
const testTree = ref(null)
// 递归查找第一个叶子节点
function findFirstLeafNode(tree) {
  for (const node of tree) {
    if (!node.clildList || node.clildList.length === 0) {
      return node.id;
    }
    const leafId = findFirstLeafNode(node.clildList);
    if (leafId) return leafId;
  }
  return null;
}
const getQuestionGroup = async () => { 
  const res = await selectAllQuestionByTreePaperBank()
  if(res.code === 20000){
    questionGroupTree.value = res.data;
    console.log("questionGroupTree.value",questionGroupTree.value);
    if(!currentGroup.value){
      currentGroup.value = findFirstLeafNode(res.data) || res.data[0]?.id;
      queryData.id = currentGroup.value;
      try {
        await nextTick();
        testTree.value.setCurrentKey(currentGroup.value); //这句报错
      } catch (error) {
        console.log(error);
      }
    }
    // getQuestionList()
    console.log("currentGroup.value",currentGroup.value);
    
    await getTableData()
  }
}
//左侧反馈列表分页器
const { queryData, tableData, getTableData,} = mixTable({
  getListApi: selectBankQuestionPagePaperBank
})
const defaultQuery = reactive({
  currentPage: 1,
  pageSize: 10,
  id: "",
  difficultyLevel: "",
  itemIdList: 3,
  keyWords: ""
})
Object.assign(queryData, defaultQuery);

const handleCurrentChange = (page) => {
  queryData.currentPage = page;
  getTableData();
}
//******组卷规则
//增加题组
const addQuestionGroup = () => {
  addChapterForm.value.paperConfig.customizationVo.itemSetConfigVoList.push({
    setName: "",
    itemNum: 0,
    itemScore: 1,
    difficultyLevel: 0,
    useArbitration: false,
    arbitrationScore: 0,
  })
}
//删除题组
const delQuestionGroup = (index) => {
  addChapterForm.value.paperConfig.customizationVo.itemSetConfigVoList.splice(index, 1);
};

const handleNodeClick = (data) => { 
  console.log("data",data);
  queryData.id = data.id;
  getTableData()
}
//题目筛选条件设置
const difficultyOption = ref([
  { label: "简单", value: '1' },
  { label: "中等", value: '2' },
  { label: "困难", value: '3' },
]);
const typeOption = ref([
  { label: "单选", value: '3' },
  { label: "多选", value: '4' },
]);
const searchCmpArray = ref([
  { label: '题目类型', key: 'itemIdList', form_type: 'select', options: typeOption.value },
  { label: '题目难度', key: 'difficultyLevel', form_type: 'select', options: difficultyOption.value },
  { label: '关键字', key: 'keyWords'}
])
const checkTest = async (row) => { 
  if(!Array.isArray(addChapterForm.value.learningTests)){
    addChapterForm.value.learningTests = []
  }
  console.log("addChapterForm.value",addChapterForm.value);
  try {
    addChapterForm.value.learningTests.push({
      progress: 50,
      questionId: row.id,
      questionName: row.cmp.label
    })
    checkQuestionVisible.value = false;
  } catch (error) {
    console.log("error",error);
  }
}
//问题删除
const delQuestion = (row) => { 
  try {
    addChapterForm.value.learningTests = addChapterForm.value.learningTests.filter(item => item.questionId !== row.questionId)
  } catch (error) {
    console.log("error",error);
  }
}

//表格展示字段
const fieldList = ref([
  {
    title: "题目名称",
    name: "name",
    width: 250,
  },
  {
    title: "类型",
    name: "questionType",
  },
  {
    title: "操作",
    name: "options",
    width: 80,
  },
]);

//问题预览
const testDialogVisible = ref(false);
const currentTestQuestion = ref([]);
const priviewQuestion = async (row) => { 
  const res = await selectByIdPaperQuestion({id: row.questionId});
  if (res.code === 20000) {
    let testQuestion = {
      ...res.data,
      formItemId: `test_${row.questionId}` // 生成唯一表单ID
    };
    testQuestion.answer = null
    currentTestQuestion.value = [testQuestion];
    console.log("题目列表", currentTestQuestion.value);
    testDialogVisible.value = true;
  }
}

//章节类型
const courseTypeOption = ref([
  { label: "章节", value: 'CHAPTER' },
  { label: "视频", value: 'VIDEO' },
  { label: "文档", value: 'DOCUMENT' },
  { label: "练习", value: 'EXERCISE' },
  { label: "测试", value: 'ASSESSMENT' },
  { label: "期末考试", value: 'FINAL_EXAM' },
]);
// const editId = ref(null);  //当前编辑信息id
// const editFlag = ref(false); //输入框显示

const columns = [
  { label: '章节名称', prop: 'name', width: '' },
  { label: '说明', prop: 'description', width: '200px' },
  { label: '类型', prop: 'type', width: '150px' },
  { label: '章节资源', prop: 'exam', width: '125px' },
  { label: '学中测试', prop: 'exam', width: '125px' },
  { label: '操作', prop: '', width: '200px' }
]
const treeLoading = ref(false)
const defaultProps = {
  children: 'children',
  label: 'name'
}

const rules = {
  pid: [{ required: true, message: '请选择上级章节', trigger: 'change' }],
  type: [{ required: true, message: '请选择章节类型', trigger: 'change' }],
  name: [{ required: true, message: '请填写章节名称', trigger: 'blur' }],
}

//级联选择器
const props1 = {
  checkStrictly: true,
  value: "id",
  label: "name",
  children: "children",
  expandTrigger: 'hover',
  multiple: false,
  emitPath: false
}

//显示期数课程编辑
const showCourseInstance = ref(false);
const confirmInstance = () => {
  showCourseInstance.value = false;
  //获取课程实例 实例数为1或0时执行对应操作
  getCourse();
 
}
//显示课程评分
const showCourseRate = ref(false);

//编辑章节对话框
const addChapterVisible = ref(false);
const addChapterFlag = ref(false);
const defaultChapterFormData = {
  courseInstanceId: "",
  pid: "",
  name: "",
  description: "",
  type: "",
  dataId: "",
  paperConfig: "",  //试卷配置
  fileName: "",
  learningTests: []
};
const addChapterForm =  ref({ ...defaultChapterFormData });

const handleChooseParent = (data,check) => {
  console.log("data",data);
  if(check){
    return
  }
  addChapterForm.value.pid = data.id
  console.log("addChapterForm.value",addChapterForm.value);
  changeFileType()
  // parentCategory.value = structuredClone(data)
}

//修改章节类型为视频或者文档时，切换显示
const fileType = ref('.mp4');
const changeFileType = () => {
  if (addChapterForm.value.type == 'VIDEO' ) {
    fileType.value = ".mp4"; 
  } else if (addChapterForm.value.type == 'DOCUMENT' ) {
    fileType.value = ".docx,.pdf,.pptx"; 

  }
  console.log("文件类型",fileType.value);
  
}

//文件预览
const previewVisible = ref(false);
const previewInfo = ref({});
const preview = async (id) => {
  const res = await getResourceDataRefer({ dataId: id });
  if(res.code == 20000){
    previewInfo.value = res.data;
    previewVisible.value = true;
  }
  console.log("previewInfo",previewInfo.value);
}
const showCheckFile = () => {
  showFilesUpload.value = true;
  //清空之前的文件信息
  changeFileType()
}
const videoOptions = reactive({
  width: '100%',
  height: '100%',
  color: '#409eff', //主题色
  title: '测试视频播放', //视频名称
  webFullScreen: false, //网页全屏
  speed: true, //进度条拖动
  muted: false, //静音
  autoPlay: true, //自动播放
  loop: false, //循环播放
  mirror: false, //镜像画面
  fluid: true,
  aspectRatio: '16:9',
  control: true, //是否显示控制器
  volume: 0.5, //默认音量0-1
  notSupportedMessage: '此视频暂无法播放，请稍后再试',
  type: "video/mp4",
  poster: '', //封面
  speedRate: [1.0, 1.25, 1.5, 2.0], // 可选的播放速度
  controlBtns: [
    'audioTrack', //音轨切换按钮
    'quality', //视频质量切换按钮
    'speedRate', //速率切换按钮
    'volume', //音量
    // 'pip', //画中画按钮
    'fullScreen' //全屏按钮
  ]
})

//根据资源id查询数据
const getResourceData = async () => { 
  if(addChapterForm.value.dataId){
    const res = await getResourceDataRefer({ dataId: addChapterForm.value.dataId });
    if(res.code === 20000){
      // addChapterForm.value.dataId = res.data.id
      addChapterForm.value.fileName = res.data.title
    }
  }
}

//新增章节
const chapterPid = ref(false)  //当前pid，用与控制增加章节时是否显示上级章节
const addChapter = (element) => { 
  // chapterPid.value = element.id
  addChapterFlag.value = true
  addChapterForm.value = { ...defaultChapterFormData };
  addChapterForm.value.dataId = ""; //清空绑定的资源id
  console.log("element",element);
  if(element && element.id){
    addChapterForm.value.pid = element.id
    chapterPid.value = true
  } else {
    //若是新增一级，pid为空
    addChapterForm.value.pid = ""
    chapterPid.value = false
  }
  addChapterVisible.value = true
}

//编辑章节信息
const editChapterInfo = (element) => {
  console.log("编辑",element);
  if(!Array.isArray(addChapterForm.value.pid)){
    addChapterForm.value.pid = [addChapterForm.value.pid]
  }
  if(!Array.isArray(addChapterForm.value.learningTests) || addChapterForm.value.learningTests == null){
    addChapterForm.value.learningTests = []
  }
  //如果已有组卷规则，检验其是否是JSON字符串
  if (addChapterForm.value.paperConfig) {
    try {
      // 尝试解析 JSON 字符串
      addChapterForm.value.paperConfig = JSON.parse(addChapterForm.value.paperConfig);
      console.log("paperConfig 解析成功:", addChapterForm.value.paperConfig);
    } catch (error) {
      // 如果解析失败，说明不是有效的 JSON 字符串
      console.error("paperConfig 解析失败:", error);
    }
  }
  //如果没有组卷规则，手动加上
  if(!element.paperConfig){
    element.paperConfig = {
      isItemRandom: false,
      label: "",
      randomWay: '1',
      useArbitration: false,
      arbitrationRate: 0,
      arbitrationScore: 0,
      customizationVo: {
        bankIdList: [],
        itemScore: 0,
        itemSetConfigVoList: [
          {
            setName: "",
            itemNum: 0,
            itemScore: 1,
            typeId: "",
            difficultyLevel: 0,
            useArbitration: false,
            arbitrationScore: 0,
          }
        ]
      },
      originFormVo: {
        isTitleRandom: false,
        originalIdList: []
      },
    }
  }
  addChapterFlag.value = false
  addChapterVisible.value = true
  addChapterForm.value = { ...element }
  getResourceData();
}
//提交章节
const appendChapter = async () => {
  addChapterForm.value.courseInstanceId = theInstance.value.id;
  if(Array.isArray(addChapterForm.value.pid)){
    addChapterForm.value.pid = addChapterForm.value.pid[0]
  }
  //检测章节绑定题目的进度不能一样
  if(addChapterForm.value.learningTests.length > 0){
    const progressSet = new Set();
    const hasDuplicateProgress = addChapterForm.value.learningTests.some(item => {
      if (progressSet.has(item.progress)) {
        return true; // 找到重复的 progress
      }
      progressSet.add(item.progress);
      return false;
    });

    if (hasDuplicateProgress) {
      ElMessage.error('绑定题目的进度不能重复，请修改后再提交！');
      return; // 阻止提交
    }
  }
  //组卷规则转JSON
  if (addChapterForm.value.paperConfig && addChapterForm.value.paperConfig != "") {
    addChapterForm.value.paperConfig = JSON.stringify(addChapterForm.value.paperConfig);
  }
  //提交
  if (addChapterFlag.value) {
    const res =  await createChapter(addChapterForm.value)
    if(res.code == 20000) {
      ElMessage.success('创建成功')
    } 
  } else {
    const res = await updateChapter(addChapterForm.value)
    if(res.code == 20000) {
      ElMessage.success('编辑成功')
    } 
  }
  addChapterVisible.value = false
  getCatalogueTree()
}

//编辑课程 章节内容
// const editChapterContent = (element) => {
//   console.log(element);
//   router.push({
//     name: 'examManageCourseContent',
//     query: {
//       chapterId: element.id,
//       chapterName: element.title,
//       type: element.type,
//     }
//   })
// } 

//删除
const remove = (element) => {
  ElMessageBox.confirm("是否删除该章节？", "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await deleteChapter({ id: element.id });
    if(res.code == 20000){
      ElMessage.success("删除成功");
      getCatalogueTree();
    }
  })
}

// 拖拽排序
const allowDrop = (draggingNode, dropNode, type) => {
  // 只允许同级拖拽，type为'prev'或'next'时是同级
  if (type === 'inner') {
    return false
  }
  // 确保是同一父节点下的拖拽
  return draggingNode.parent === dropNode.parent
}
//拖拽排序结束
const handleNodeDragEnd = async (draggingNode, dropNode, dropType, ev) => { 
  console.log("handleNodeDragEnd",draggingNode, dropNode, dropType, ev);
  const res = await reorderSameLevelChapters({
    // courseInstanceId: theInstance.value.id,
    // parentId: dropNode.data.pid,
    draggedId: dropNode.data.id,
    targetId: draggingNode.data.id,
  })
  //如果出错再次获取章节数据
  if(res.code != 20000){
    getCatalogueTree();
  }
}

//更改当前课程实例
const togInstance = async (item) => {
  theInstance.value = item
  await getCatalogueTree()
}

//获取课程目录树
const catalogueTree = ref([])
const getCatalogueTree = async () => {
  const res = await getCourseChapterTree({ courseInstanceId: theInstance.value.id })
  catalogueTree.value = res.data
  console.log("目录树",catalogueTree.value);
}

//获取当前课程 对应实例
const courseData = ref({})
const instanceList = ref([])
const getCourse = async () => {
  const res = await selectByIdCourse({id: theCourseId}); 
  courseData.value = res.data; 
  const instanceRes = await selectPageInstance({courseIds: courseIds});
  instanceList.value = instanceRes.data.list;
  if(instanceList.value.length == 0) {
    ElMessage.warning('当前课程没有期数课程，请先创建期数课程');
    return;
  } else if(instanceList.value.length == 1) {
    theInstance.value = instanceList.value[0];
    getCatalogueTree();
  }
}

//课程实例增加考试
const checkExam = ref(false)
const examRef = ref(null)

//确认选择试卷
const confrimCheckExam = async () => { 
  checkExam.value = false
  if (examRef.value) {
    let exam = examRef.value.getExam()
    console.log("选择试卷",exam);
    addChapterForm.value.paperName = exam[0];
    addChapterForm.value.paperId = exam[0];
  }
}

//*******文件上传
const uploadVisible = ref(false)

// 附件上传
const showFilesUpload = ref(false)
const resourceFormList = ref([])
// const fileName = ref("")
const fileUrl = ref("")
const insertFiles = (filesList,res) => {
  console.log("filesList",filesList);
  console.log("res",res);
  resourceFormList.value = filesList.map(item => {
    return {
      resourceData: {
        title: item.name,
        url: item.url,
        uid: item.uid,
      },
      needUpload: item.needUpload,
      tagList: item.tagList || [],
    }
  })
  console.log("resourceFormList.value",resourceFormList.value);
  addChapterForm.value.fileName = resourceFormList.value[0].resourceData.title;
  
  fileUrl.value = resourceFormList.value[0].resourceData.url
  if(res){
    addChapterForm.value.dataId = res[0].id
  } else {
    addChapterForm.value.dataId = resourceFormList.value[0].resourceData.uid
  }
  console.log("addChapterForm.value",addChapterForm.value);

}

//课程实例绑定讲师
const showCourseLeacturer = ref(false);
const instanceLeacturerList = ref([]);
const leacturerList = ref([]);
const addOneLeaturer = ref(null);
const addLeaturer = ref(false); //是否显示添加讲师下拉框
//新增讲师绑定课程实例
const addOneLeaturerChange = async () => {
  console.log("选择的讲师",addOneLeaturer.value);
  const res = await bindLecturer({
    lecturerId: addOneLeaturer.value,
    courseInstanceId: theInstance.value.id,
  });
  if(res.code == 20000) {
    ElMessage.success('绑定讲师成功');
    await getInstanceLeacturer();
    addOneLeaturer.value = null; //清空选择
    addLeaturer.value = false; //隐藏添加讲师下拉框
  } else {
    ElMessage.error('绑定讲师失败');
  }
}
//解绑讲师和课程实例
const nobindLeacturer = async (item) => {
  ElMessageBox.confirm("是否解绑该讲师？", "解绑确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await unbindLecturer({
      lecturerId: item.id,
      courseInstanceId: theInstance.value.id,
    });
    if(res.code == 20000) {
      ElMessage.success('解绑讲师成功');
      await getInstanceLeacturer();
    } else {
      ElMessage.error('解绑讲师失败');
    }
  })
}
//获取当前实例讲师
const getInstanceLeacturer = async () => {
  const res = await getCourseInstanceLecturersLecturer({courseInstanceId: theInstance.value.id}); 
  if(res.code == 20000) {
    instanceLeacturerList.value = res.data;
  } else {
    ElMessage.error('获取讲师信息失败');
  }
}
//获取所有讲师列表
const getLeacturer = async () => {
  const res = await pagingLecturer({ currentPage: 1, pageSize: 1000 });
  if(res.code == 20000) {
    leacturerList.value = res.data.list;
  } else {
    ElMessage.error('获取讲师信息失败');
  }
}
onMounted(async () => {
  await getCourse();
  //当前实例初始化为1
  theInstance.value = instanceList.value[instanceList.value.length - 1]
  await getCatalogueTree();
  await getInstanceLeacturer();
  await getLeacturer();
  await getQuestionGroup();
})
</script>

<style scoped lang="scss">
.setting-header{
  display: flex;
  align-items: center;
  p{
    font-size: 14px;
    color: $black;
  }
  span{
    color: $black_2;
  }
}
.category-tree{
  :deep(.el-tree-node__content){
    height: 45px;
    border-bottom: 1px solid $borderColor;
    padding-left: 0 !important; 
  }
  :deep(.el-tree-node__label){
    width: 100%;
  }
}

.leacturer-list{
  display: flex;
  align-items: center;
  p{
    color: $black_2;
    font-size: 16px;
  }
  .leacturer-item{
    margin-left: 10px;
    padding-right: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
    .lecturer-avatar{
      width: 50px;
      height: 50px;
      border-radius: 50%;
      overflow: hidden;
      box-shadow: 0 0 5px rgba(0,0,0,0.1);
      img{
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    .name{
      text-align: center;
      margin-top: 3px;
      color: $black;
    }
    .nobind-icon{
      position: absolute;
      right: -4px;
      top: 0;
      font-size: 16px;
      color: #666;
      display: none;
      font-weight: bold;
      &:hover{
        color: $mainColor;
      }
    }
    &:hover{
      .nobind-icon{
        display: block;
      }
    }
  }
}
.option-row{
  margin-top: 20px;
  display: flex;
  align-items: center;
  .add-leaturer{
    margin-right: 10px;
  }
}
.custom-tree-node {
  display: flex;
  align-items: center;
  font-size: 14px;
  width: 100%;
  box-sizing: border-box;
  .tree-cell {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    white-space: pre-wrap;
    word-wrap: break-word;
    word-break: break-word;
  }
  .name-cell {
    width: calc(100% - 800px) ;
    flex-shrink: 0;
  }

  .description-cell {
    width: 200px;
    flex-shrink: 0;
  }
  .exam-cell{
    width: 125px;
    flex-shrink: 0;
  }
  .test-cell{
    width: 125px;
    flex-shrink: 0;
  }
  .type-cell {
    display: flex;
    /* flex: 1; */
    width: 150px;
  }

  .operation-cell {
    width: 200px;
    flex-shrink: 0;
    gap: 8px;
    i {
      color: $mainColor;
    }
  }
}
.cascader-p{
  &.disabled-item{
    opacity: 0.5;
  }
}
.el-dropdown {
  margin-right: 10px;
}
.table-header {
  display: flex;
  align-items: center;
  padding-left: 46px;
  height: 40px;
  background: #eff3f8;
  border-bottom: 1px solid #c0c6cc;

  .table-header-label {
    box-sizing: border-box;
    font-size: 14px;
    color: #000000;
  }
}
.top-info{
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  margin-top: 10px;
  .right-box{
    display: flex;
    button{
      margin-left: 10px;
    }
  }
}
.tips{
  color: var(--el-color-primary-light-3);
  font-size: 12px;
  line-height: 16px;
  margin-top: 5px;
  width: 100%;
}
.info-row{
  display: flex;
  align-items: center;
  gap: 10px;

}
.button-box{
  display: flex;
  padding-right: 10px;
  .el-button--primary.is-link{
    &:after {
      display: inline-block;
      position: relative;
      margin: 0 8px;
      height: 12px;
      content: "";
      border-left: 1px solid #cbcbcb;
    }
    &:last-child:after {
      display: none;
    }
  }
  .el-button+.el-button{
    margin-left: 0;
  }
  flex-grow: 0;
  position: relative;
  i{
    position: absolute;
    right: -13px;
    top: 5px;
    color: $mainColor;
    cursor: pointer;
  }
}
.file-name{
  width: 100%;
  background: #eee;
  padding: 2px 10px;
  border-radius: 2px;
  font-size: 12px;
  color: $black;
  margin-top: 5px;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-wrap: break-word;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  display: -webkit-box;
}
/* 选择题目对话框设置 */
.check-question-container{
  display: flex;
  .left-tree{
    width: 160px;
    /* padding-right: 10px; */
    box-sizing: border-box;
    margin-right: 10px;
    border-right: 1px solid $borderColor;
    :deep(.el-tree-node__content){
      height: 36px;
    }
  }
  .right-question-list{
    flex: 1;
    .question-name{
      /* 显示一行 超出省略 */
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 100%;
      display: block;
      height: 18px;
      line-height: 18px;
      font-size: 14px;
      color: $black;
    }
  }
}
.addChapter-dialog{
  .test-list{
    width: 100%;
    margin-top: 20px;
    padding: 10px;
    background: white;
    border-radius: 8px;
    box-sizing: border-box;
    border: 1.5px dashed $borderColor;
  }
  .test-item{
    display: flex;
    align-items: center;
    &.header{
      margin-bottom: 5px;
      font-weight: bold;
    }
    .test-name{
      flex: 1;
      padding-left: 10px;
      box-sizing: border-box;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 100%;
    }
    .right-option{
      display: flex;
      width: 80px;
      i{
        font-size: 16px;
        color: $black_2;
        margin: 0 5px;
        &:hover{
          color: $mainColor;
        }
      }
    }
  }


}
</style>
